package com.xiaofeng.student.auth;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import com.xiaofeng.student.service.UserService;

public class MyAuthenticationProvider implements AuthenticationProvider {

	   @Autowired
	   UserService us;
	   
		
		@Override	// TODO Auto-generated method stub
		public Authentication authenticate(Authentication authentication) throws AuthenticationException {
			//第4篇讲过的其他参数，默认details类型中包含用户ip和sessionId
			WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
			//用户名和密码
			String username = authentication.getName(); 	
			String password = authentication.getCredentials().toString(); 
			//根据以上参数，自定义认证逻辑，系统默认实现就是在此读取UserDetails认证密码
			if(us.get(username, password)==null){
				throw new BadCredentialsException("密码错误");				
			}
			// 认证通过，从数据库中查询用户权限 
			List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
			authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
			//生成已认证Authentication，系统会将其写入SecurityContext
			return new UsernamePasswordAuthenticationToken(username, password, authorities);
		}

	

	@Override
	public boolean supports(Class<?> authentication) {
		// TODO Auto-generated method stub
		return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
	}

}
